<template>
	<!-- <div class="p-4"> -->
	<div class="container">
		<el-page-header content="填写问卷" @back="goBack" />

		<!-- 基础字段 -->

		<div class="survey-form">
			<!-- 标题栏 -->
			<div class="form-title">以下内容由调查员填写</div>
			<div class="survey-content">
				<!-- 第一行：问卷编码 + KISH码 + 表信息 -->
				<div class="row">
					<!-- 问卷编码 -->
					<div class="card code-section">
						<div class="card-title">问卷编码</div>
						<div class="code-inputs">
							<div class="code-box">
								<el-input v-model="answers.monitoringPointNumber" />
								<span class="label">监测点</span>
							</div>
							<div class="code-box">
								<el-input v-model="answers.townNumber" />
								<span class="label">乡镇</span>
							</div>
							<div class="code-box">
								<el-input v-model="answers.villageNumber" />
								<span class="label">村</span>
							</div>
							<div class="code-box">
								<el-input v-model="answers.familyNumber" />
								<span class="label">家庭户</span>
							</div>
						</div>
					</div>

					<!-- KISH码 -->
					<div class="card kish-section">
						<div class="card-title">KISH码</div>
						<div class="kish-code">
							<div class="circle">
								<span class="kish-text">B1</span>
							</div>
						</div>
					</div>

					<!-- 表信息 -->
					<div class="card info-section">
						<div>表　　号：卫健统 74 表</div>
						<div>制定机关：国家卫生健康委</div>
						<div>批准机关：国家统计局</div>
						<div>批准文号：国统制〔2025〕53号</div>
						<div>有效期至：2028年2月</div>
					</div>
				</div>

				<!-- 第二行：负责人 + 问卷填写人 -->
				<div class="row">
					<!-- 负责人 -->
					<div class="card person-section">
						<div class="card-title">负责人</div>
						<div class="form-pairs">
							<div class="pair">
								<span>调查员</span>
								<el-input v-model="answers.investigator" />
								<span>调查日期</span>
								<el-input v-model="answers.surveyDate" />
							</div>
							<!-- <div class="pair">
								<span>质控员</span>
								<el-input v-model="answers.qc" />
								<span>核查日期</span>
								<el-input v-model="answers.qcDate" />
							</div> -->
						</div>
					</div>

					<!-- 问卷填写人 -->
					<div class="card fill-section">
						<div class="card-title">问卷填写人</div>
						<el-radio-group v-model="answers.finishMethod" class="radio-group">
							<el-radio :value="'1'">① 自填完成</el-radio>
							<el-radio :value="'2'">② 因文化程度低，面对面调查</el-radio>
							<el-radio :value="'3'">③ 因其他原因，面对面调查</el-radio>
						</el-radio-group>
						<!-- <el-input
						v-if="form.fillPersonType === 3"
						v-model="form.fillPersonOther"
						placeholder="请输入原因"
						maxlength="50"
						show-word-limit
					/> -->
					</div>
				</div>
			</div>
		</div>

		<!-- 元数据字段 -->

		<div class="survey-invitation">
			<!-- 顶部蓝色标题栏 -->
			<div class="section-title">以下内容由受访者自己/调查员协助完成</div>
			<div class="survey-content">
				<!-- 问候语 -->
				<div class="greeting">
					您好！国家卫生健康委正在开展全国居民健康素养调查，调查结果是评价全国居民健康素养水平、
					制定健康相关政策的重要依据。您被选中参加本次调查，您的参与对我们非常重要，回答的内容将会被严格保密，
					不会对个人产生任何不利影响。
				</div>

				<!-- 子标题栏 -->
				<div class="section-subtitle">如果您愿意参加本次调查，请点击下方按钮并选择时间和地点</div>

				<!-- 按钮与日期 -->
				<div class="form-row">
					<el-button type="primary">确认参与</el-button>
					<el-date-picker
						v-model="answers.date"
						type="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						placeholder="选择日期"
						class="date-picker"
					/>
				</div>

				<!-- 地址信息 -->
				<div class="form-grid">
					<div class="input-with-label">
						<el-input v-model="answers.province" />
						<span class="suffix-label">省（自治区、直辖市）</span>
					</div>
					<div class="input-with-label">
						<el-input v-model="answers.city" />
						<span class="suffix-label">市</span>
					</div>
					<div class="input-with-label">
						<el-input v-model="answers.county" />
						<span class="suffix-label">县（市、区）</span>
					</div>
					<div class="input-with-label">
						<el-input v-model="answers.street" />
						<span class="suffix-label">街道（乡镇）</span>
					</div>
					<div class="input-with-label">
						<el-input v-model="answers.village" />
						<span class="suffix-label">居委员会（村）</span>
					</div>
				</div>

				<!-- 底部说明 -->
				<div class="thanks">感谢您的支持与配合！</div>
			</div>
		</div>

		<el-form ref="formRef" :model="answers" label-width="140px" class="mt-4">
			<!-- 基础字段 -->
			<!-- <div class="flex gap-4">
				<el-form-item
					v-for="field in template.fields"
					:label="field.label"
					:key="field.id"
					:prop="field.id"
					:rules="
						field.required ? [{ required: true, message: field.label + '为必填项', trigger: 'blur' }] : []
					"
				>
					<el-input v-model="answers[field.id]" :maxlength="field.inputs * 10" />
				</el-form-item>
			</div> -->

			<!-- 元数据字段 -->
			<!-- <div class="flex gap-4 mt-4">
				<el-form-item
					v-for="(meta, key) in template.metadata"
					:label="meta.label"
					:key="key"
					:prop="key"
					:rules="
						meta.required ? [{ required: true, message: meta.label + '为必填项', trigger: 'change' }] : []
					"
				>
					<component
						:is="getComponent(meta.type)"
						v-model="answers[key]"
						v-bind="getProps(meta)"
						class="vertical-group"
					/>
				</el-form-item>
			</div> -->

			<!-- 问卷章节 -->
			<div v-for="section in template.sections" :key="section.title" class="mt-6">
				<h3 class="text-lg font-semibold title">{{ section.title }}</h3>

				<div v-for="q in section.questions" :key="q.id" class="mb-4 section-content">
					<div class="font-medium text-base mb-1">
						<span v-if="q.required" style="color: red; margin-right: 4px">*</span>{{ q.id }}. {{ q.label }}
					</div>

					<el-form-item
						:prop="q.id"
						label-width="20px"
						:rules="q.required ? [{ required: true, message: '请选择 ' + q.label, trigger: 'change' }] : []"
						class="m-0"
					>
						<component
							:is="getComponent(q.type)"
							v-model="answers[q.id]"
							v-bind="getProps(q)"
							class="vertical-group"
						/>
					</el-form-item>
				</div>
			</div>
		</el-form>

		<div class="mt-4 flex gap-2">
			<el-button type="primary" @click="handleSave">保存草稿</el-button>
			<el-button @click="goBack">关闭</el-button>
		</div>

		<el-dialog v-model="dialogVisible" title="保存成功">
			<span>保存成功，是否开始新问卷？</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="close">否</el-button>
				<el-button type="primary" @click="startNew">是</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElInput, ElDatePicker, ElCheckbox } from 'element-plus';
import { saveSurvey, getSurveyById } from '@/db/localDb';
import { useAutoSave } from '@/composables/useAutoSave';
import PhotoUpload from '@/components/PhotoUpload.vue';
import RadioWithSub from '@/components/RadioWithSubInput.vue';
import CheckboxWithSub from '@/components/CheckboxWithSubInput.vue';
import Baseinfo from './components/Baseinfo.vue';
import SurveyInvitation from './components/SurveyInvitation.vue';

const componentMap: Record<string, any> = {
	input: ElInput,
	date: ElDatePicker,
	radio: RadioWithSub,
	checkbox: CheckboxWithSub,
	// checkbox: ElCheckbox,
	photo: PhotoUpload,
};

const getComponent = (type: string) => componentMap[type] || ElInput;

const getProps = (item: any) => {
	const base: any = {};

	if (item.type === 'date') {
		base.type = 'date';
		base.placeholder = '请选择日期';
		base.style = { width: '180px' };
	}

	if (['radio', 'checkbox'].includes(item.type)) {
		base.options = Array.isArray(item.options) ? item.options : []; // ✅ 保证 options 始终为数组
	}
	return base;
};

const route = useRoute();
const router = useRouter();
const template = ref({ fields: [], metadata: {}, sections: [] });
const answers = reactive<Record<string, any>>({});
const dialogVisible = ref(false);
const formRef = ref();
const draftId = (route.query.id as string) || crypto.randomUUID();
const title = computed(() => {
	const mp = answers.monitoringPointNumber;
	const town = answers.townNumber;
	const village = answers.villageNumber;
	return mp && town && village ? `${mp}_${town}_${village}_全国居民健康素养监测调查问卷` : `自动保存`;
});

const isReady = ref(false);

useAutoSave(draftId, answers, isReady, { title });

const loadTemplate = async () => {
	const res = await fetch('/converted_health_survey_with_checkbox.json');
	template.value = await res.json();
	template.value.fields.forEach((f: any) => {
		if (!(f.id in answers)) answers[f.id] = '';
	});

	Object.keys(template.value.metadata).forEach((k) => {
		if (!(k in answers)) {
			answers[k] = template.value.metadata[k].type === 'checkbox' ? [] : '';
		}
	});

	template.value.sections.forEach((s: any) => {
		s.questions.forEach((q: any) => {
			if (!(q.id in answers)) answers[q.id] = q.type === 'checkbox' ? [] : '';
		});
	});
};

onMounted(async () => {
	await loadTemplate();
	const saved = await getSurveyById(draftId);
	console.log('saved', saved);
	if (saved) {
		Object.assign(answers, saved.answers);
		// title = saved.title || '';
		// console.log('saved', saved);
	}
	isReady.value = true;
});

const handleSave = () => {
	formRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		try {
			await saveSurvey({
				id: draftId,
				title: title.value,
				fileName: title.value,
				answers: JSON.parse(JSON.stringify(answers)),
			});
			dialogVisible.value = true;
		} catch (e: any) {
			ElMessage.error('保存失败: ' + e.message);
		}
	});
};

const goBack = () => router.push('/list');
const startNew = () => {
	Object.keys(answers).forEach((k) => {
		answers[k] = Array.isArray(answers[k]) ? [] : '';
	});
	dialogVisible.value = false;
};
const close = () => {
	dialogVisible.value = false;
	nextTick(() => {
		goBack();
	});
};
</script>

<style scoped>
.container {
	width: 97vw;
	height: 100vh;
	padding: 10px;
	position: relative;
}
.title {
	background: #6b9bd2;
	color: #fff;
	padding: 6px 10px;
	font-weight: bold;
}
.section-content {
	padding: 5px 20px;
}
.vertical-option {
	display: block;
	margin: 4px 0;
}
.vertical-group {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	gap: 4px;
}

.survey-form {
	font-family: 'Microsoft YaHei', sans-serif;
	font-size: 14px;
	padding: 10px;
	color: #333;
}

.survey-content {
	padding: 20px;
}

.form-title {
	background-color: #6b9bd2;
	color: white;
	padding: 8px 16px;
	font-weight: bold;
	font-size: 16px;
}

.row {
	display: flex;
	margin-top: 12px;
	gap: 10px;
}

/* 问卷编码区域 */
.code-section {
	/* flex: 6; */
	width: 60%;
}

.kish-section {
	/* flex: 1; */
	display: flex;
	width: 10%;
	flex-direction: column;
	justify-content: flex-start;
	align-items: center;
}

.info-section {
	/* flex: 3; */
	/* 宽度为30%再减去10px */
	width: calc(30% - 10px);
	font-size: 13px;
	padding: 10px;
	border: 1px solid #ddd;
	/* height: 100%; */
	box-sizing: border-box;
}

.card {
	border: 1px solid #ccc;
	/* padding: 10px; */
	box-sizing: border-box;
	background-color: #fff;
}

.card-title {
	background-color: #a7c3e7;
	font-weight: bold;
	padding: 4px 8px;
	margin-bottom: 10px;
	font-size: 14px;
}

.code-inputs {
	display: flex;
	/* justify-content: space-between; */
	padding: 10px;
	align-items: flex-end;
	gap: 12px;
}

.code-box {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 100px;
}

.code-box .el-input {
	text-align: center;
}

.label {
	margin-top: 4px;
	font-size: 13px;
}

/* KISH码样式 */
.kish-code {
	display: flex;
	justify-content: center;
	align-items: center;
}

.circle {
	border: 2px dashed red;
	border-radius: 50%;
	width: 80px;
	height: 80px;
	display: flex;
	justify-content: center;
	align-items: center;
}

.kish-text {
	font-size: 20px;
	color: red;
	font-weight: bold;
}

/* 第二行 */
.person-section {
	/* flex: 6; */
	width: 60%;
}

.fill-section {
	/* flex: 4; */
	width: 40%;
}

.form-pairs {
	display: flex;
	flex-direction: column;
	padding: 10px;
	gap: 12px;
}

.pair {
	display: flex;
	align-items: center;
	gap: 10px;
}

.pair span {
	white-space: nowrap;
	width: 70px;
	text-align: right;
}

.radio-group {
	display: flex;
	flex-direction: column;
	gap: 8px;
	margin-bottom: 4px;
}

/* 元数据CSS */

.survey-invitation {
	background: #fff;
	padding: 10px;
	font-size: 16px;
}

.survey-content {
	padding: 20px;
}

.section-title {
	background-color: #6b9bd2;
	color: white;
	padding: 8px 12px;
	font-weight: bold;
}

.greeting {
	margin: 16px 0;
	line-height: 1.6;
	color: #333;
	font-weight: 600;
}

.section-subtitle {
	background-color: #d0def3;
	padding: 8px 12px;
	font-weight: bold;
	margin: 20px 0 16px;
	color: #333;
}

.form-row {
	display: flex;
	align-items: center;
	gap: 20px;
	margin-bottom: 20px;
}

.date-picker {
	width: 160px;
}

.form-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
	margin-bottom: 20px;
}

.input-with-label {
	display: flex;
	align-items: center;
	width: 350px;
}

.input-with-label .el-input {
	flex: 1;
}

.suffix-label {
	margin-left: 8px;
	white-space: nowrap;
	font-size: 14px;
	color: #444;
}

.thanks {
	font-size: 15px;
	color: #333;
}
</style>
